using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using cframework_xlua;
using System.ComponentModel;
using Newtonsoft.Json;
namespace cframework_xlua
{
    [EssentialTools("xcodebuild", "https://developer.apple.com/xcode/")]
    [CreateAssetMenu(menuName = "cframework_xlua/PublishUtil_Ipa")]
    public class PublishUtil_Ipa : PlatformPublishUtil
    {
        public override bool BuildAndPublish(BuildPlayerSetting setting, BuildPlayerSetting.PublishInfo publishInfo)
        {
            string outputAppPath = publishInfo.buildOutputPath + $"/{publishInfo.appName}_{setting.platform}_{setting.subPlatform}_{setting.publishType}";

         
            if (setting.platform == cframework_xlua.Platform.ios)
            {
                if (!BuildIpaFromProject(setting, publishInfo.outputProjectPath, outputAppPath))
                {
                    return false;
                }
            }

            return PublishApps(setting, outputAppPath);
        }


        static bool PublishApps(BuildPlayerSetting setting, string destDirPath)
        {
            string searchExtName = null;
            if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android)
            {
                searchExtName = "*.apk";
            }
            else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.iOS)
            {
                searchExtName = "*.ipa";
            }

            if (string.IsNullOrEmpty(searchExtName))
            {
                return false;
            }

            {
                string[] apkPaths = System.IO.Directory.GetFiles(destDirPath, searchExtName);
                string downloadUrl = null;
                foreach (var a in apkPaths)
                {
                    if (setting.channelUtil && setting.channelUtil.Deploy(setting, a, null, null, ref downloadUrl))
                    {
                        setting.StartHttpServer();
                    }
                }

                if (!string.IsNullOrEmpty(downloadUrl))
                {
                    Debug.Log("pgy url: " + " " + downloadUrl);
                    if (EditorUtility.DisplayDialog("download url", downloadUrl, "copy", "ok"))
                    {
                        GUIUtility.systemCopyBuffer = downloadUrl;
                    }
                }
            }

            return true;
        }

        static bool BuildIpaFromProject(BuildPlayerSetting setting, string outputProjectPath, string destDirPath)
        {
            string outputPath = System.IO.Path.GetDirectoryName(destDirPath).Replace("\\", "/");

            //string outputStr = null;
            //string errorStr = null;
            // if(CommandLineTool.CmdExWithOutput("chmod", "+x build_libil2cpp.sh", projectPath + "/HybridCLRData/iOSBuild", false, true, ref outputStr, true, ref errorStr) != 0)
            // {
            //     Debug.LogError("output: " + outputStr);
            //     Debug.LogError("error: " + errorStr);
            //     return;
            // }
            // else
            // {
            //     if(CommandLineTool.CmdExWithOutput(shPath, "build_libil2cpp.sh", projectPath + "/HybridCLRData/iOSBuild", false, true, ref outputStr, true, ref errorStr) != 0)
            //     {
            //         Debug.LogError("output: " + outputStr);
            //         Debug.LogError("error: " + errorStr);
            //         return;
            //     }
            // }

            var scheme_name = "Unity-iPhone";
            var UseModernBuildSystem = "NO";
            var XCODEBUILD_PATH = setting.deviceToolPaths.GetCmdToolPath("xcodebuild");
            var buildWorkspaceStr = "";
            if (System.IO.Directory.Exists($"{outputProjectPath}/{scheme_name}.xcworkspace"))
            {
                buildWorkspaceStr = $"-workspace {scheme_name}.xcworkspace";
            }
            var param = $"clean archive {buildWorkspaceStr} -scheme {scheme_name} -archivePath {outputPath}/{scheme_name}.xcarchive BUILD_DIR={outputProjectPath} -allowProvisioningUpdates -UseModernBuildSystem={UseModernBuildSystem}";

            var ret = CommandLineTool.RunCommand2(XCODEBUILD_PATH, param, outputProjectPath);
            if (ret.ExitCode != 0)
            {
                Debug.LogError("output: " + ret.StdOut);
                Debug.LogError("error: " + ret.StdErr);
                return false;
            }
            else
            {
                var export_method = "ad-hoc";
                var ipaName = export_method;

                var infoStr = $@"<?xml version=""1.0"" encoding=""UTF-8""?>
                        <!DOCTYPE plist PUBLIC ""-//Apple//DTD PLIST 1.0//EN"" ""http://www.apple.com/DTDs/PropertyList-1.0.dtd"">
                        <plist version=""1.0"">
                        <dict>
                            <key>signingStyle</key>
                            <string>automatic</string>
                            <key>method</key>
                            <string>{export_method}</string>
                            <key>iCloudContainerEnvironment</key>
                            <string>Development</string>
                            <key>stripSwiftSymbols</key>
                            <true/>
                            <key>compileBitcode</key>
                            <true/>
                        </dict>
                        </plist>
                        ";

                var plistFilePath = $"{outputPath}/{export_method}AUTOMATICExportOptions.plist";
                System.IO.File.WriteAllText(plistFilePath, infoStr);



                var param2 = $"-exportArchive -archivePath {outputPath}/{scheme_name}.xcarchive -exportPath {destDirPath} -exportOptionsPlist {plistFilePath} -allowProvisioningUpdates";
                var ret2 = CommandLineTool.RunCommand2(XCODEBUILD_PATH, param2, outputProjectPath);
                if (ret2.ExitCode != 0)
                {
                    Debug.LogError("output: " + ret2.StdOut);
                    Debug.LogError("error: " + ret2.StdErr);
                    return false;
                }
            }

            return true;
        }
    }
}